// namespace -> FTPUI
// invoke the function,pass FTPUI into it, in the case that it doesn't exist, pass an object literal
var FTPUI = (function (FTPUI) {
  
  FTPUI.remoteEntry = null;
  FTPUI.localEntry = null;
  FTPUI.curLocalDir = null;

  FTPUI.createRemoteDir = function (session, directoryListing) {
    console.log("in create remote dir");
    this.session = session;
    try {
      FTPUI.listRemote(directoryListing);
    }
    catch (error) {
      FTPUI.notifyUI("Could not access remote directory. " + error);
    }
  };

  FTPUI.listRemote = function (directoryListing) {
    try {
      var $serverList = $('#remote-browser');
      $serverList.prop('textContent', '');
      var entries = FTPUtils.parseLsDirectoryListing(directoryListing);
      for (var i = 0; i < entries.length; i++) {
        var $li = $('<li>');
        var $link = $('<a>');
        var entryInfo = entries[i];
        var entryName = entryInfo.name;
        var filePerm = entryInfo.permissions;

        var lastModDate = entryInfo.date;
        var size = entryInfo.size;
        if (!entryInfo.isFile) {
          $link.addClass('listed-dir');
        }
        else if (entryInfo.isLink === 0) {
          $link.addClass('link-file');
        }
        else {
          $link.addClass('listed-file');
        }

        $link.prop('textContent', entryName);
        $link.appendTo($li);
        jQuery.data($link, 'size', entryInfo.size);
        jQuery.data($link, 'fullPath', entryName);
        $li.appendTo($serverList);
        FTPUI.handleRemoteEntry($link);
      }
    }
    catch (error) {
      throw error;
    }
  };

  FTPUI.handleRemoteEntry = function ($remoteEntry) {
    var session = this.session;
    var self = this;
    $remoteEntry.dblclick(function () {
      if ($remoteEntry.hasClass('listed-dir')) {
        self.handleDirNavigation($remoteEntry);
      }
    });
    $remoteEntry.click(function () {
      if (FTPUI.remoteEntry) {
        FTPUI.handleSelect(FTPUI.remoteEntry);
      }
      FTPUI.handleSelect($remoteEntry);
      FTPUI.remoteEntry = $remoteEntry;
    });
  };

  FTPUI.handleSelect = function(entry) {
      entry.toggleClass('selected');
  };

  FTPUI.handleDirNavigation = function ($remoteEntry) {
    var session = this.session;
    console.log("We have clicked on a directory", $remoteEntry.text())
    console.log($remoteEntry.text());
    session.getCurrentDir().then(function (currentDir) {
      session.changeWorkingDir($remoteEntry.text());
      FTPUI.remoteEntry = null;
      return currentDir;
    }).then(function (currentDir) {
      var dir = currentDir + $remoteEntry.text();
      return session.listDir(dir);
    }).then(function (dirListing){
      console.log(dirListing);
      FTPUI.listRemote(dirListing);
    }).catch(function (error) {
      FTPUI.notifyUI("Could not get directory listing. " + error);
    });
  };

  //FTP COMMAND: CDUP -> recieve unixOutput from LIST
  // listremote(directoryListing)
  FTPUI.handleRemoteBackButton = function () {
    var session = this.session;
    $('#remote-back').click(function() {
      session.changeToParentDir().then(function () {
        return session.getCurrentDir();
      }).then(function (currentDir) {
        return session.listDir(currentDir);
      }).then(function (dirListing) {
        FTPUI.listRemote(dirListing);
      }).catch(function (error) {
        FTPUI.notifyUI('Could not move to parent directory. ' + error);
      });
    });
  };

  FTPUI.handleLocalButtons = function() {
    $('#choose-directory').click(function() {
      chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function (entry) {
        if (entry) {
          // if the user hits cancel, entry will be undefinied!
          FTPUI.curLocalDir = entry;
          FTPUI.listLocalDir(entry);
        }
        // local back button functionality 
        $('#local-back').click(function() {
          try {
              FTPUI.visitParent(FTPUI.curLocalDir);
          } catch (error) {
              console.log(err.message);
          }
        });
      });
    });
  };

  FTPUI.handleDownload = function() {
    var session = this.session;
    $('#download').click(function() {
      console.log("handle download")
      if (!FTPUI.remoteEntry || !FTPUI.curLocalDir) {
         // local or remote entry not selected
        return;
      }
      else {
        FTPUI.handleSelect(FTPUI.remoteEntry);
        if (!FTPUI.localEntry) {
          //get local dir and download it ther 
          FTPUI.localEntry = FTPUI.curLocalDir;
        }
        if (FTPUI.localEntry.isFile) {
          //output message
          FTPUI.notifyUI('Can\'t Download to File');
          return;
        }
        session.getCurrentDir().then(function (currentDir) {
          var entrySize = jQuery.data(FTPUI.remoteEntry, 'size');
          var fullPath = currentDir + FTPUI.remoteEntry.text();
          jQuery.data(FTPUI.remoteEntry, 'fullPath', fullPath);
          return session.download(FTPUI.remoteEntry, FTPUI.localEntry);
        }).then(function (value) {
          FTPUI.remoteEntry = null;
          FTPUI.localEntry = null;
          FTPUI.listLocalDir(FTPUI.curLocalDir);
        });
      }
    });
  };

  FTPUI.getRemoteDirEntriesInfo = function(dirPath) {
    var session = this.session;
    return session.listDir(dirPath).then(function (directoryListing) {
       return FTPUtils.parseLsDirectoryListing(directoryListing);
    });
  };
			
	FTPUI.visitParent = function(entry) {
		entry.getDirectory('..', {create: false}, FTPUI.listLocalDir);
	};
  
  FTPUI.listLocalDir = function (entry) {
    FTPUI.curLocalDir = entry;
    FileSystemUtils.getLocalDirContents(entry).then(function (dirContent) {
      FTPUI.displayEntries(dirContent);
    }).catch(function (error) {
      throw error;
      FTPUI.notifyUI("Cannot display local directory" + error);
    });
  };

  FTPUI.displayEntries = function (entries) {
     var $element = $('#local-browser');
    // clear the current entries
    $element.prop('textContent', '');
    // Array.forEach paremeters (value of $element,index of $element, the arrayObject itself)
    entries.forEach(function (entry, i, entries) {

      var $li = $('<li>');
      var $link = $('<a>');
      if (entry.isDirectory) {
          $link.prop('textContent', entry.name += '/');
          $link.addClass('listed-dir');
      } else {
          $link.prop('textContent', entry.name);
          $link.addClass('listed-file');
      }

      //add anchor tag to li $element
      $link.appendTo($li);

      //add li $element to un-ordered $element list
      $li.appendTo($element);
      FTPUI.handleLocalEntry($link, entry);
    });
  };

  FTPUI.handleLocalEntry = function ($localEntry, entryObject) {
    $localEntry.dblclick(function() {
      if ($localEntry.hasClass('listed-dir')) {
        FTPUI.listLocalDir(entryObject);
        FTPUI.localEntry = null;
      } else {
        FTPUI.notifyUI('Selected Local File: ' +  $localEntry.text());
      }
    });
    $localEntry.click(function () {
      FTPUI.handleSelect($localEntry);
      FTPUI.localEntry = entryObject;
    });
  };

    /* Send the User message updates */
  /* @param Type: String or Error Object*/
  FTPUI.notifyUI = function (notification) {
    if(typeof notifcation === Error) notification.toString();
    var $li = $('<li>');
    $li.prop('textContent', notification);
      $('#ui-message').append($li);
  };

  return FTPUI;


}(FTPUI || {}));
